<template>
  <div class="settle-page">
    <div class="product-info">
      <div class="product-card">
        <img
          class="product-img"
          :src="productInfo.logo"
          :alt="productInfo.name"
        />
        <div class="product-info-left">
          <div class="product-name">{{ productInfo.name }}</div>
          <!-- <div class="product-period">
            {{ t('gpuinfo_agreeFirst') }}：{{ productInfo.cycle }} {{ t('products_day') }}
          </div> -->
        </div>
        <div class="product-info-right">
          <div class="product-price">
            COP{{ formatNumber(productInfo.price) }}
          </div>
          <div class="product-quantity">X1</div>
        </div>
      </div>
    </div>

    <div class="payment-section">
      <div class="section-title">{{ t('settle_selectWallet') }}</div>
      <div
        class="wallet-option"
        :class="{ active: selectedWallet === '1' }"
        @click="selectedWallet = '1'"
      >
      {{ t('profile_walletDeposit') }} (COP{{ formatNumber(balances.deposit || "0") }})
        <van-icon v-if="selectedWallet === '1'" name="success" />
      </div>
      <div
        class="wallet-option"
        :class="{ active: selectedWallet === '2' }"
        @click="selectedWallet = '2'"
      >
      {{ t('profile_walletIncome') }} (COP{{ formatNumber(balances.income || "0") }})
        <van-icon v-if="selectedWallet === '2'" name="success" />
      </div>
    </div>

    <div class="bottom-bar">
      <div class="total">
        <span class="label">{{ t('settle_total') }}</span>
        <span class="amount">COP{{ formatNumber(productInfo.price) }}</span>
      </div>
      <div class="invest-btn" @click="toPay">{{ t('settle_investNow') }}</div>
    </div>

    <!-- 加载状态 -->
    <div class="loading-container" v-if="loading">
      <van-loading type="spinner" color="#f6eade" size="28px" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from "vue";
import {
  showConfirmDialog,
  showToast,
  showLoadingToast,
  closeToast,
} from "vant";
import { useRouter, useRoute } from "vue-router";
import { addLockOrder } from "@/api/products";
import { formatNumber } from "@/utils/public";
import { useUserStore } from "@/stores";

const { t } = useI18n()
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const loading = ref(false);
const selectedWallet = ref("1"); // 默认选择存款钱包

// 从store获取用户信息，使用类型断言表明这是一个扩展的用户信息类型
const userInfo = computed(() => userStore.userInfo || {}) as any;

// 产品信息
const productInfo = reactive({
  id: "",
  name: "",
  price: "",
  logo: "",
  cycle: "",
});

// 从用户信息中获取钱包余额
const balances = reactive({
  get deposit() {
    return formatNumber(userInfo.value.inusable || "0");
  }, // 存款钱包余额
  get income() {
    return formatNumber(userInfo.value.yuusable || "0");
  }, // 收入钱包余额
});

// 初始化产品信息
const initProductInfo = () => {
  const { id, name, price, logo, cycle } = route.query;
  
  if (!id || !price || !name || !logo || !cycle) {
    showToast(t('settle_infoIncomplete'));
    router.back();
    return false;
  }
  
  productInfo.id = id as string;
  productInfo.name = name as string;
  productInfo.price = price as string;
  productInfo.logo = logo as string;
  productInfo.cycle = cycle as string;
  
  return true;
};

// 投资支付
const toPay = async () => {
  // 检查钱包余额是否足够
  const isDepositWallet = selectedWallet.value === "1";
  const walletBalance = isDepositWallet
    ? userInfo.value.inusable
    : userInfo.value.yuusable;
  const productPrice = parseFloat(productInfo.price.replace(/,/g, ""));
  const balance = parseFloat(String(walletBalance || "0").replace(/,/g, ""));

  if (balance < productPrice) {
    showConfirmDialog({
      message: `${isDepositWallet ? t('settle_depositNotEnough') : t('settle_incomeNotEnough')}`,
      confirmButtonText: t('settle_yes'),
      cancelButtonText: t('settle_no'),
      className: "settleDialog"
    })
      .then(() => {
        router.push("/user/recharge");
      })
      .catch(() => {
        console.log("Pembayaran gagal");
      });
    return;
  }

  try {
    loading.value = true;
    showLoadingToast({
      message: t('settle_processing'),
      forbidClick: true,
    });

    const res = await addLockOrder({
      id: productInfo.id,
      wallet: selectedWallet.value,
    });

    closeToast();
    loading.value = false;

    if (res.code === 200) {
      showToast(res.msg);
      router.push("/user/gpu");
    } else {
      showToast(res.msg || t('settle_investFail'));
    }
  } catch (error) {
    closeToast();
    loading.value = false;
    console.error("Investasi gagal", error);
    showToast(t('products_networkError'));
  }
};

// 页面加载时初始化产品信息和获取用户信息
onMounted(async () => {
  initProductInfo();

  // 确保获取最新的用户信息
  try {
    await userStore.info();
  } catch (error) {
    console.error("err", error);
  }
});
</script>

<style scoped>
.settle-page {
  min-height: 100vh;
  overflow: hidden;
  padding: 5px 0 74px 0;
  color: #f6eade;
  background: url("@/assets/images/login/topBg.png") no-repeat top;
  background-size: 100% auto;
  position: relative;
}

.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.product-info {
  border-bottom: 0.5px solid rgba(153, 153, 153, 0.2);
  border-top: 0.5px solid rgba(153, 153, 153, 0.3);
  padding: 11px;
  background-color: rgba(254, 242, 230, 0.05);
}

.product-card {
  display: flex;
}

.product-img {
  width: 103px;
  height: 80px;
  border-radius: 8px;
  border: 0.5px solid rgba(153, 153, 153, 0.2);
}

.product-info-left {
  margin-left: 17px;
  width: 229px;
  display: flex;
  align-items: center;
}
.product-info-left .product-period {
  color: rgb(153, 153, 153);
  margin-top: 5px;
  font-size: 12px;
}
.product-info-right{
  display: flex;
  align-items: center;
}

.product-info-right .product-quantity {
  color: rgb(153, 153, 153);
  margin-top: 4px;
  font-size: 12px;
}

.payment-section {
  border-bottom: 0.5px solid rgba(153, 153, 153, 0.2);
  border-top: 0.5px solid rgba(153, 153, 153, 0.2);
  padding: 11px;
  border-radius: 0px;
  background-color: rgba(254, 242, 230, 0.05);
  margin-top: 22px;
}

.section-title {
  height: 34px;
  line-height: 34px;
}

.wallet-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 40px;
  line-height: 40px;
  background-color: hsla(0, 0%, 60%, 0.15);
  color: #999;
  font-weight: 400;
  padding: 0 11px;
  border-radius: 5px;
  margin: 11px 5px;
  font-size: 14px;
}

.wallet-option.active {
  background:
    linear-gradient(270deg, #fee5cf, #dfb695 50%, #fee5cf),
    linear-gradient(180deg, #af917f 2%, #a9836b 99%);
  color: #211a18;
  font-weight: 700;
}

.wallet-option :deep(.van-icon) {
  font-size: 16px;
}

.wallet-option.active :deep(.van-icon) {
  color: #211a18;
}

.bottom-bar {
  display: flex;
  position: fixed;
  bottom: 0px;
  left: 0px;
  right: 0px;
  width: 100%;
  justify-content: space-between;
  border-top: 0.5px solid rgba(153, 153, 153, 0.2);
  height: 51px;
}

.total {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  height: 51px;
  display: flex;
  align-items: center;
  padding-left: 11px;
  font-size: 19px;
  font-weight: bold;
}

.total .label {
  font-size: 13px;
  color: rgb(248, 61, 61);
  font-weight: normal;
}

.total .amount {
  margin-left: 5px;
  color: rgb(248, 61, 61);
}

.invest-btn {
  width: 183px;
  height: 51px;
  line-height: 51px;
  border-radius: 0;
  background:
    linear-gradient(270deg, #fee5cf, #dfb695 50%, #fee5cf),
    linear-gradient(180deg, #af917f 2%, #a9836b 99%);
  text-align: center;
  font-size: 18px;
  font-weight: 700;
  color: #0c1f26;
}
</style>
